<?php
/**
 * Loader.php
 * 
 * @category    Madoqua
 * @package     Loader
 */

/** Zend_Loader */
require_once 'Zend/Loader.php';

/**
 * Madoqua_Loader
 * 
 * a loader for forms and models from module directories (which aren't in the include path)
 * 
 * @category    Madoqua
 * @package     Loader
 */
class Madoqua_Loader
{
    /**
     * load a (set of) models
     *
     * @param string|array $model
     * @return void
     */
    public static function loadModel($models)
    {
        $models = (array) $models;
        //treat models as array
        
        $frontController = Madoqua_Application::getFront();
        //the fc
        
        $modules = Madoqua_Application::getModules();
        //all modules
        
        $directories = $frontController->getControllerDirectory();
        foreach($directories as $module => $directory) {
            $directories[$module] = realpath($directory . '/../models/');
        }
        //find directory for models in each module

        foreach ($models as $model) {
            //for every model to load
            
            if (class_exists($model)) {
                //it has already been loaded, woo! \ó/
                continue;
            }
            
            $split = explode('_', $model);
            
            if (count($split) == 1) {
                //model existed of only a single part
                $requestedModule = $frontController->getDefaultModule();
                //assume default module
            } else {
                //module existed of Modulename_And_More
                $requestedModule = array_shift($split);
                //assume first part is module name
            }
            //find requested module from the model
            
            $moduleKey = strtolower($requestedModule[0]);
            if (strlen($requestedModule) > 1) {
                $moduleKey .= substr($requestedModule, 1);
            }
            //module key (has lower case first char)

            if (!in_array($moduleKey, $modules)) {
                throw new Exception('Model ' . $model . ' has a module "' . $requestedModule . '" which does not exist');
            }
            //check module is allright
            
            $file = $directories[$moduleKey];
            //base directory
            foreach($split as $part) {
                $file .= DIRECTORY_SEPARATOR . $part;
            }
            $file .= '.php';
            //build file from parts of the model

            Zend_Loader::loadFile(basename($file), dirname($file));
            //load it (or well.. at least *try* to load it)

            if (!class_exists($model)) {
                throw new Exception ('Model ' . $model . ' not loaded');
            }
            
        }

    }
}